package com.springmvc.platform.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


/**
 * @author zhouhong
 * @create 2017/9/16
 * @modify
 */
@Controller
@RequestMapping("")
public class LoginController {
    private final static Logger LOGIN_LOGGER = LoggerFactory.getLogger(LoginController.class);
    //跳转登陆页面
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    //跳转登陆页面
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String doLogin(String username , String password, RedirectAttributes ra){
        //验证用户是否已经登录
        Subject subject= SecurityUtils.getSubject();
        //如果未验证通过，进行验证
        if(!subject.isAuthenticated()){
            //获取用户名密码封装为token
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            //进行登陆验证
            try {
                subject.login(token);
            }catch (Exception e){
                LOGIN_LOGGER.error("用户{}登陆失败",username,e);
                ra.addFlashAttribute("loginError", "账号或密码有误.");
                return "redirect:/login";
            }
            //登陆成功
            return "redirect:/index";
        }
        return "redirect:/index"; // 若已经登录，则直接跳转工作台
    }
}
